<template>
  <div class="user-container">
    <el-row v-show="!isShowGroup" :gutter="20" v-loading="userLoading">
      <el-col :span="6" :xs="24" :sm="24" :md="6" :lg="6" :xl="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>组织结构</span>
          <div style="display:flex;justify-content:end;margin-top:10px">
            <el-checkbox v-if="userOuter" style=" margin-left:10px" v-model="isShowOuter">外部单位</el-checkbox>
            <el-checkbox   v-model="isShowGroup">群组</el-checkbox>
          </div>
          </div>
          <el-tree class="filter-tree" ref="tree" :data="treeList" :props="departmentProps" node-key="id"
            @check-change="handChange" @node-click="handleNodeClick"></el-tree>
        </el-card>
      </el-col>
      <el-col :span="12" :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-card class="box-card marginTop">
          <div slot="header" class="clearfix">
            <span>选择人员</span>
          </div>
          <div class="filter-container">
            <el-form :inline="true" @submit.native.prevent>
              <el-form-item>
                <el-input size="mini" placeholder="输入姓名或工号" v-model="username" clearable @keyup.native.prevent="handSearchUser"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button class="filter-item" size="mini" type="primary" icon="el-icon-search" @click="handSearchUser">
                  搜索</el-button>
                <!-- <el-button
                   v-if="!isRadio"
                  class="filter-item"
                  size="mini"
                  icon="el-icon-plus"
                  :disabled="!multipleSelection.length"
                  @click="addSelectUser"
                >添加选中用户</el-button> -->
              </el-form-item>
              <el-form-item>
                  <el-button class="filter-item" size="mini" type="primary" v-if="isCanSelect"  @click="handSelectAll">
                  全选</el-button>
                  <el-button class="filter-item" size="mini" type="primary" v-else @click="handCancelSelectAll">
                  取消全选</el-button>
              </el-form-item>
            </el-form>
          </div>
          <div class="task-items">
            <el-table ref="userTable" :data="usersList" size="small" stripe style="text-align: center;"
              @select="handleSelectionChange" 
              @row-click="handleRowClick" 
              >
              <el-table-column v-if="isRadio" label width="40">
                <template scope="scope">
                  <el-radio :label="scope.row.id" v-model="radioUser"
                    @change.native="getRadioSelectRow(scope.$index,scope.row)">&nbsp;</el-radio>
                </template>
              </el-table-column>
              <el-table-column v-else type="selection" width="55"></el-table-column>
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column v-if="isShowOuter" prop="username" label="单位名称"></el-table-column>
              <el-table-column v-if="!isShowOuter" prop="first_name" label="姓名"></el-table-column>
              <el-table-column v-if="!isShowOuter" prop="job_no" label="用户工号"></el-table-column>
            </el-table>
            <pagination class="pageWrapper" v-show="total>0" :total="total" :layout="'total, prev, pager, next'"
              :page.sync="currentPage" :limit.sync="pageSize" @pagination="handlePage" />
          </div>
        </el-card>
      </el-col>
      <el-col :span="6" :xs="24" :sm="24" :md="6" :lg="6" :xl="6">
        <el-card class="box-card marginTop table">
          <el-row slot="header" type="flex" justify="space-between" style="align-items: center;">
            <span>已选中用户({{sureUsersList.length || 0}}人)</span>
            <el-button v-if="showSaveSelectedUser" type="primary" size="mini" @click="onSelectUsers(sureUsersList, groupSelection)"
          >确 定</el-button
        >
          </el-row>
          <div class="task-items">
            <el-table :height="sureUsersList.length > 10 ? 530 : null" :data="sureUsersList" size="small">
              <el-table-column v-if="isShowOuter" prop="username" label="单位名称"></el-table-column>
              <el-table-column v-if="!isShowOuter" prop="first_name" label="姓名"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="text" size="small" @click="removeUesr(scope.row.id)">移除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <div v-show="isShowGroup">
      <share-group ref="shareGroup" @toggleShowGroup="isShowGroup = false" @selectGroup="handleSelectGroup"/>
    </div>
  </div>
</template>
<script>
  import {
    getUserLabel,
    getUserDepartment,
    getOuterUserDepartment
  } from "@/api/user.js";
  import user from "../../../../store/modules/user";
  
  import {
    mapGetters
  } from 'vuex'
  export default {
    name: "userManager",
    data() {
      return {
        username: "",
        radioUser: "",
        usersList: [], // 用户列表
        usersListTemp: [],
        multipleSelection: [], // 表格选择
        sureUsersList: [],
        labelList: [],
        departmentList: [],
        outerDepartList: [],
        treeList: [],
        checkList: [],
        userLoading: false, // 加载
        isSelect: true,
        isShowOuter: false,
        isShowGroup: false, // 是否显示群组
        groupSelection: [], // 是否显示群组
        selectNodes: [],
        selectUsers: [],
        selectUserFilter: [],
        departmentProps: {
          children: "child",
          label: "dt_name"
        },
        currentPage: 1,
        total: 0,
        pageSize: 10,
        isCanSelect:true,//控制
        lastSelect:[], //上次选择
        lastSelectGroup:[],//上次选择群组
      };
    },
    computed: {
      ...mapGetters([
        'id'
      ])
    },
    props: {
      relateUsers: {
        type: Array
      },
      initUsers: {
        type: Array,
        default: () => []
      },
      isRadio: {
        type: Boolean,
        default: false
      },
      showSaveSelectedUser: {
        type: Boolean,
        default: true
      },
      outerSelected: {
        type: Boolean,
        default: false
      },
      userOuter: {
        type: Boolean,
        default: true
      },
      shareGroup: {
        type: Boolean,
        default: false
      },
      onSelectUsers: {
        type: Function
      }
    },
    watch: {
      relateUsers(val) {
        if (val) {
          this.sureUsersList = val
        }
      },
      initUsers(val) {
        this.handleClearSelect()
        if (val) {
          this.sureUsersList = this.getUserById(val, this.usersListTemp)
        }
      },
      isShowOuter(flag){
        this.toggleUsers(flag)
      },
      // isShowGroup(status) {
      //   status && (this.sureUsersList = [])
      // },
      groupSelection(val){
        let arr = []
        for(let item of this.groupSelection){
            arr = arr.concat(item.userinfo)
        }
        this.sureUsersList = [...this.sureUsersList,...arr]
      },
      outerSelected:{
        handler(newVal) {
          getOuterUserDepartment({owner: this.id}).then(
            res =>{
              this.outerDepartList = res.data
              this.isShowOuter = true
            }
          )
        },
        immediate: false
      }
    },
    components: {
      'Pagination': require('@/components/Pagination').default,
       ShareGroup: () => import('@/views/markSys/components/ShareGroup')
    },
    created() {
      this.requestDepartments();
      this.requestOuterDepart()
    },
    methods: {
      toggleUsers(flag){
        this.clearSelect()
        const list = flag ? this.outerDepartList : this.departmentList
        this.updateDepart(list)
      },
      // 清空选择
      clearSelect() {
        if(this.isShowGroup) {
          this.$refs.shareGroup.clearActionData()
        }else {
          this.$refs.userTable && this.$refs.userTable.clearSelection()
          this.sureUsersList = []
          this.radioUser = ''
        }
      },
      // 选择用户分页
      handlePage() {
        let size = this.pageSize,
          page = this.currentPage;
        const start = (page - 1) * size;
        const end = page * size;
        this.usersList = this.usersListTemp.slice(start, end);
        this.sureIsSelectInTable()
      },
      // 点击节点
      handleNodeClick(data) {
        const arr = [];
        arr.push(data);
        const list = this.getUsersList(arr, [])
        this.total = list.length
        this.usersListTemp = list;
        this.usersList = list.slice(0, this.pageSize);
        this.currentPage = 1
        const isSelect = this.sureIsSelectInTable()
        const bole = this.sureIsCanSelect(isSelect)
        this.isCanSelect = bole
      },
      //判断是否可以全选了
      sureIsCanSelect(isSelect){
        const len = isSelect.length
        if(this.total > 10){
          if(len == 10){
            return false
          }else{
            return true
          }
        }else{
          if(len >= this.total){
            return false
          }else{
            return true
          }
        }
      },
      // 搜索用户
      handSearchUser(name) {
        const list = this.usersListTemp.filter(
          e => e.job_no && e.job_no.indexOf(this.username) > -1 || e.first_name && e.first_name.indexOf(this.username) > -1
        );
        this.usersList = list.slice(0, this.pageSize);
        this.total = list.length
        this.currentPage = 1
        this.sureIsSelectInTable()
      },
      // 用户单选
      getRadioSelectRow(index, row) {
        const arr = [];
        arr.push(row);
        this.sureUsersList = arr;
        this.$emit('setSelectUsers', this.sureUsersList)
      },
      // 表格多选
      handleSelectionChange(val) {
        if(this.lastSelect.length > val.length){
          const user = this.handleCancelUser(this.lastSelect,val)
          this.handleDeleteUser(user)
        }
        this.multipleSelection = val;
        this.addSelectUser()
        this.lastSelect = val
      },
      //点行单选
      handleRowClick(val){
        if(this.isRadio){
          const arr = []
          arr.push(val)
          this.sureUsersList = arr;
          this.radioUser = val.id
          this.$emit('setSelectUsers',this.sureUsersList)
        }else{
              let newMultiple
              if(this.lastSelect.includes(val)){
                this.$refs.userTable.toggleRowSelection(val,false)
                newMultiple = [...this.lastSelect]
                newMultiple.forEach((el,index) =>{
                  if(JSON.stringify(el) == JSON.stringify(val)){
                      newMultiple.splice(index,1)
                  }
                })
                this.handleDeleteUser([val])
              }else{
                this.$refs.userTable.toggleRowSelection(val,true)
                newMultiple = [...this.lastSelect]
                newMultiple.push(val)
                this.multipleSelection = newMultiple
              this.addSelectUser()
              }
              this.lastSelect = newMultiple
        }

      },
      //群组多选
      handleSelectGroup(rows){
        let arr = []
        for(let item of this.lastSelectGroup){
          for(let el of item.userinfo){
            arr.push(el)
          }
        }
        this.handleDeleteUser(arr)
        this.groupSelection = rows
        this.lastSelectGroup = rows
      },
      //判断谁被取消了
      handleCancelUser(lastSelect,nowSelect){
        const arr = lastSelect.filter(el => !nowSelect.includes(el))
        return arr
      },
      //从已全选列表中剔除被移除用户
      handleDeleteUser(userList){
        const newSureList = this.sureUsersList.filter(el => !userList.includes(el))
        this.sureUsersList = newSureList
      },
      //全选
      handSelectAll(){
        this.multipleSelection = this.usersListTemp
        this.usersListTemp.forEach(el =>{
          this.$refs.userTable.toggleRowSelection(el)
        })
        this.addSelectUser()
        this.isCanSelect = false
      },
      //取消全选
      handCancelSelectAll(){
        this.multipleSelection = []
        this.$refs.userTable.clearSelection()
        for(let index in this.sureUsersList){
          for(let el of this.usersListTemp){
            if(JSON.stringify(this.sureUsersList[index]) == JSON.stringify(el)){
              this.sureUsersList.splice(this.sureUsersList[index],1)
            }
          }
        }
        this.isCanSelect = true
      },
      // 清空表格选择
      handleClearSelect() {
        this.multipleSelection = []
        this.$refs.userTable.clearSelection()
      },
      // 添加用户
      addSelectUser() {
        if (!this.sureUsersList) {
          this.sureUsersList = []
        }
        
        let list = [...this.sureUsersList,...this.multipleSelection]
        let hash = {};
        this.sureUsersList = list.reduce((item, next) => {
          if (!hash[next.id]) {
            hash[next.id] = true;
            item.push(next);
          }
          return item;
        }, []);
        this.$emit('setSelectUsers', this.sureUsersList)
        // this.$refs.userTable.clearSelection()
      },
      // 移除用户
      removeUesr(userId) {
        if (this.isRadio) this.radioUser = "";
        let index = null
        let list = []
        this.sureUsersList = this.sureUsersList.filter(e => e.id !== userId);

        this.multipleSelection.forEach((item, i) => {
          if (item.id === userId) {
            index = i
            list.push(item)
          }
        })
        if (list) {
          list.forEach(row => {
            this.$refs.userTable.toggleRowSelection(row);
          });
        }
        if (!this.sureUsersList.length) {
          this.$refs.userTable.clearSelection();
        }
        // 移除用户选中状态
        this.multipleSelection.splice(index, 1)
        list = []
        this.$emit('setSelectUsers', this.sureUsersList)
        // this.$refs.userTable.clearSelection()
      },
      //判断用户是否在列表里
      sureIsSelectInTable(){
        let arr = []
        for(let item of this.usersList){
          for(let el of this.sureUsersList){
              if(JSON.stringify(item) == JSON.stringify(el)){
                arr.push(item)
              }
          }
        }
        this.lastSelect = arr
        setTimeout(()=>{
          arr.forEach(row =>{
           this.$refs.userTable.toggleRowSelection(row)
        })
        },50)
        return arr;
      },
      handChange() {
        const keys = this.$refs.tree.getCheckedKeys();
        this.selectNodes = keys.filter(e => {
          return typeof e !== "string";
        });
      },
      // 通过initData获取对应用户信息
      getUserById(initUsers, list) {
        const result = []
        if (!initUsers) return
        initUsers.forEach(
          id => {
            list.forEach(
              e => {
                if (id === e.id) {
                  result.push(e)
                }
              }
            )
          }
        )
        return result
      },
      // 设置组织结构，用户列表
      updateDepart(depart){
        const list = this.getUsersList(depart, [])
        this.total = list.length
        this.usersList = list.slice(0, this.pageSize);
        this.usersListTemp = list.concat();

        this.treeList = depart;
      },
      // 请求外部单位
      async requestOuterDepart(){
        getOuterUserDepartment({owner: this.id}).then(
          res =>{
            this.outerDepartList = res.data
          }
        )
      },
      requestDepartments() {
        this.userLoading = true
        getUserDepartment({owner: this.id}).then(res => {
          this.departmentList = res.data;
          const len = this.departmentList.length
          // if(this.departmentList[len - 1].id == 10000){
          //   this.departmentList.pop()
          // }
          if(!this.outerSelected){
            this.updateDepart(this.departmentList)
          }

          if (this.initUsers) {
            const list = this.getUsersList(this.departmentList, [])
            this.sureUsersList = this.getUserById(this.initUsers, list)
            this.$emit('setSelectUsers', this.sureUsersList)
          }
          this.userLoading = false
        }).catch(e =>{
          this.userLoading = false
        })
      },
      getUsersList(data, result) {
        data.forEach(item => {
          // result = [...result, ...item.user_department]
          item.user_department.forEach(user => {
            result.push(user);
          });
          if (item.child && item.child.length > 0) {
            this.getUsersList(item.child, result);
          }
        });
        return result;
      },
      formatData(data) {
        data.forEach((item, i, arr) => {
          item.id = "depart" + item.id;
          item.disabled = arr[i] && arr[i].length ? false : true;
          item.username = item["dt_name"] ? item["dt_name"] : item["name"];
        });
        return data;
      }
    }
  };

</script>
<style lang="scss">
  .user-container{
    height: 65vh;
  }
  @media screen and (max-width: 500px) {
    .user-container{
      height: auto;
    }
  }
  .user-container {
    @media screen and (max-width: 500px){
        .marginTop{
          margin-top:10px !important;
        }
    }
    .box-card{
      height: 65vh;
      overflow: scroll;
    }
    .table{
      overflow: hidden;
    }
    .pageWrapper {
      margin-top: 5px;
    }

    .filter-tree {
      min-height: 100px;
      overflow: auto;
    }
    .el-card__body {
      padding: 5px 10px 10px;
    }

    .el-form-item {
      margin-bottom: 0;
    }
  }

</style>
<style>
</style>
